<template>
  <div class="bg-white">
    <el-page-header @back="back">
      <template slot="title">
        <span class="back">返回</span>
      </template>
      <template slot="content">
        <span class="back pr-4">预警</span>
      </template>
    </el-page-header>
    <div class="pa-10">
      <avue-form ref="form" v-model="form" :option="option" :defaults.sync="defaults" @submit="submit">
        <template slot="ruleList">
          <RuleList ref="rulelist" :user-list.sync="userList" :user-label.sync="userLabel" :disabled="isDetail" />
        </template>
        <template slot="pushDetail">
          <el-row>
            <el-col :span="4">
              <el-select v-model="form.triggerTimesType" placeholder="请选择">
                <el-option label="连续" value="continuous" />
                <el-option label="累计" value="accumulate" />
              </el-select>
            </el-col>
            <el-col :span="2" style="text-align: center">触发</el-col>
            <el-col :span="3"
              ><el-input-number v-model="form.triggerTimesNum" :min="0" style="width: 100%"></el-input-number
            ></el-col>
            <el-col :span="4" style="padding-left: 16px">次时推送</el-col>
          </el-row>
        </template>
        <template slot="userList">
          <div>
            <el-radio-group v-model="userLabel" size="small">
              <el-radio-button
                v-for="(item, index) in userList"
                :key="index"
                :label="'规则' + ['一', '二', '三'][index]"
              ></el-radio-button>
            </el-radio-group>
            <UserSelecter
              v-model="userList[userIndex]"
              :show-input="true"
              style="margin-top: 10px"
              :disabled="isDetail"
            >
            </UserSelecter>
          </div>
        </template>
        <template slot="cronExpression">
          <Expression v-model="form.cronExpression" :disabled="isDetail"></Expression>
        </template>
        <template slot="menuForm" slot-scope="{ size }">
          <el-button type="primary" :size="size" @click="$refs.form.submit()">提交</el-button>
          <!-- <el-button plain :size="size" @click="$refs.form.resetForm()">暂存</el-button> -->
          <el-button :size="size" @click="back">取消</el-button>
        </template>
      </avue-form>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { warningGet, warningAdd, warningEdit } from '@/api/warning'
import moment from 'moment'
import RuleList from './components/ruleList.vue'
import Expression from '@/components/expression'
import UserSelecter from '@/components/userSelecter'
export default {
  components: { RuleList, Expression, UserSelecter },
  props: {},
  data() {
    return {
      loading: true,
      form: {},
      defaults: {},
      option: {
        detail: this.$route.path.includes('detail'),
        submitBtn: false,
        emptyBtn: false,
        menuPosition: 'left',
        menuLeft: false,
        labelWidth: 120,
        labelSuffix: ' ',
        group: [
          {
            label: '基础信息',
            arrow: true,
            prop: 'basic',
            column: [
              {
                label: '预警名称',
                prop: 'warningName',
                span: 12,
                rules: [{ required: true, message: '请输入预警名称' }],
              },
              {
                label: '预警类型',
                prop: 'warningType',
                type: 'select',
                span: 12,
                rules: [{ required: true, message: '请选择预警类型' }],
                dicData: [
                  { label: '指标预警', value: '指标预警' },
                  { label: '目标预警', value: '目标预警' },
                  { label: '综合预警', value: '综合预警' },
                ],
              },
              {
                label: '责任部门',
                prop: 'responsibleDeptId',
                type: 'tree',
                props: {
                  label: 'name',
                  value: 'deptId',
                },
                dicUrl: '/api/dept/tree',
                dicMethod: 'post',
                dicQuery: {},
                search: true,
                rules: [{ required: true, message: '请选择责任部门' }],
                addDisabled: false,
                span: 12,
                align: 'left',
                overHidden: true,
              },
              {
                label: '责任人',
                prop: 'responsibleUserId',
                type: 'select',
                span: 12,
                rules: [{ required: true, message: '请选择责任人' }],
                dicUrl: '/api/user/userGrid/1/999',
                props: {
                  label: 'nickName',
                  value: 'userId',
                },
                dicMethod: 'post',
                dicFormatter: (res) => res.listObject,
              },
              {
                label: '预警描述',
                prop: 'warningDesc',
                span: 24,
                type: 'textarea',
              },
            ],
          },
          {
            label: '预警规则',
            arrow: true,
            prop: 'rule',
            column: [
              {
                label: '',
                prop: 'ruleList',
                span: 24,
                labelWidth: 0,
              },
            ],
          },
          {
            label: '预警推送',
            arrow: true,
            prop: 'waringPushBo',
            column: [
              {
                label: '消息模板',
                dicUrl: '/noticeTemplate/list',
                props: {
                  label: 'templateName',
                  value: 'id',
                },
                dicMethod: 'post',
                dicFormatter: (res) => res,
                prop: 'msgTemplate',
                type: 'select',
                span: 12,
                row: true,
                dicData: [],
              },
              {
                label: '推送人员',
                prop: 'userList',
                span: 12,
                row: true,
              },
              {
                label: '推送频率',
                prop: 'pushRateType',
                type: 'select',
                span: 12,
                row: true,
                dicData: [
                  { label: '实时推送', value: 'real-time' },
                  { label: '触发次数推送', value: 'trigger-times' },
                ],
                rules: [{ required: true, message: '请选择推送频率' }],
                control: (e) => {
                  this.$set(this.defaults.pushDetail, 'display', e === 'trigger-times')
                },
              },
              {
                label: '',
                prop: 'pushDetail',
                labelWidth: '',
                span: 24,
              },
            ],
          },
          {
            label: '数据监测',
            arrow: true,
            prop: 'monitor',
            column: [
              {
                label: '监测时间范围',
                prop: 'dateRange',
                type: 'datetimerange',
                span: 12,
                row: true,
                control: (e) => {
                  this.form.startTime = moment(e[0]).format('YYYY-MM-DD 00:00:00')
                  this.form.endTime = moment(e[1]).format('YYYY-MM-DD 23:59:59')
                },
                rules: [{ required: true, message: '请选择监测时间范围' }],
              },
              {
                label: '监测频率',
                prop: 'monitorRate',
                type: 'select',
                span: 12,
                row: true,
                dicData: [
                  { label: '仅执行一次', value: 'one' },
                  { label: '简单重复执行', value: 'repeat' },
                ],
                rules: [{ required: true, message: '请选择监测频率' }],
                control: (val) => {
                  this.$set(this.defaults.cronExpression, 'display', val === 'repeat')
                },
              },
              {
                label: '执行时间设置',
                prop: 'cronExpression',
                rules: [{ required: true, message: '请填选执行时间设置' }],
                span: 24,
                row: true,
              },
            ],
          },
        ],
      },
      userList: [],
      userLabel: '规则一',
    }
  },
  computed: {
    ...mapGetters(['name']),
    userIndex() {
      return ['规则一', '规则二', '规则三'].findIndex((item) => item === this.userLabel)
    },
    isAdd() {
      return this.$route.path.includes('add')
    },
    isDetail() {
      return this.$route.path.includes('detail')
    },
    isEdit() {
      return this.$route.path.includes('edit')
    },
  },
  mounted() {
    this.init()
  },
  methods: {
    submit(_, done) {
      if (this.$refs.rulelist) {
        this.$refs.rulelist
          .validate()
          .then((res) => {
            let { msgTemplate, pushRateType, triggerTimesNum, triggerTimesType } = this.form
            let waringPushBo = {
              msgTemplate,
              pushRateType,
              triggerTimesNum,
              triggerTimesType,
            }
            let params = { ...this.form, ...res, waringPushBo }
            let fn = warningAdd
            if (params.id) {
              fn = warningEdit
            }
            fn(params).then((res) => {
              if (res.success) {
                this.$message.success(this.isEdit ? '修改成功' : '创建成功')
                this.$router.back()
              }
            })
          })
          .catch((err) => {
            console.log(err)
            done()
          })
      } else {
        done()
      }
    },
    async init() {
      let id = this.$route.params.id
      if (id) {
        let res = await warningGet({ id })
        let { waringRuleBoList, waringPushBo, startTime, endTime } = res.data
        this.form = { ...res.data, ...waringPushBo, dateRange: [startTime, endTime] }
        this.$nextTick(() => {
          this.$refs.rulelist.init(waringRuleBoList)
        })
      } else {
        this.$refs.rulelist.init([])
      }
    },
    back() {
      this.$router.back()
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep .el-page-header {
  background-color: #ffff;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

::v-deep .el-page-header__content {
  font-size: 16px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  color: #262626;
}

.bg-white {
  min-height: 100%;
}

// @import './style/index.scss';

.chart-form-detail {
  background: #fff;
}

::v-deep {
  .el-table__fixed-right::before,
  .el-table__fixed::before {
    background-color: transparent;
  }
}
</style>
